<?php

// **************************************************************
// | Name: 星空框架 购物车分店铺处理 方法
// **************************************************************
// | Version: V5.0
// **************************************************************
// | Author: xkyinzhe <zhonghuaxinxing@sina.cn>
// **************************************************************
// | City: 青岛
// **************************************************************
// | Time: 2021-08-28 15：59
// **************************************************************
declare(strict_types=1);

namespace app\common\services;

use app\common\model\Store;
use app\common\model\Goods;
use app\common\model\SpecPrice;
use app\common\model\Car;
use app\common\services\ShippingServices;

/**
 * @xk 购物车服务管理
 */
class CarServices
{
    /**
     * @xk 确认订单参数相关
     *
     * @method getMakeSureList
     * @param  array           $list                      [description]
     * @param  array           $address_info              [description]
     * @return [type]          [description]
     * @Time   2021-10-21
     * @City   青岛
     * @Author xkyinzhe        <zhonghuaxinxing@sina.cn>
     */
    public static function getMakeSureList($list = [], $address_info=[])
    {
        $storeModel = new Store();
        $goodsModel = new Goods();
        $specPriceModel = new SpecPrice();
        $carModel = new Car();
        $shippingServices = new ShippingServices();
        $store_list = []; // 仓库列表
        if ($list) {
            foreach ($list as $key => $value) {
                $store_id = $value['store_id']; // 仓库id
                // 获取仓库信息
                $store_info = $storeModel
                        ->field('`store_id`,`status`,`is_self`')
                        ->find($store_id);
                if (!$store_info || $store_info['status'] != 1) {
                    continue;
                }
                // 第二步判断 产品状态
                $goods_info = $goodsModel
                    ->where([['goods_id','=',$value['goods_id']]])
                      ->field('`goods_id`,`store_id`,`goods_name`,`picurl`,`selling_price`,`weight`,`stock`,`is_onsell`,`achievement_bili`,`bonus_type`,`bonus_price`,`next_bonus_price`,`vip_buy_bili`')
                      ->find();
                if (!$goods_info || $goods_info['is_onsell'] != 1) {
                    continue;
                }
                $cart_data = [];
                $value['goods_name'] = $cart_data['goods_name'] = $goods_info['goods_name'];
                $value['goods_id'] = $cart_data['goods_id'] = $goods_info['goods_id'];
                $value['store_id'] = $cart_data['store_id'] = $goods_info['store_id'];
                $value['achievement_bili'] = $cart_data['achievement_bili'] = $goods_info['achievement_bili'];
                $value['goods_pic'] = $cart_data['goods_pic'] = $goods_info['picurl'];
                $value['goods_price'] = (float)$cart_data['goods_price'] = (float)$goods_info['selling_price'];
                $value['selling_price'] = (float)$cart_data['selling_price'] = (float)$goods_info['selling_price'];
                if ($value['is_buy'] == 1) {
                    $value['goods_price'] = $cart_data['goods_price'] = sprintf('%.2f', (float)$goods_info['selling_price']*(float)$goods_info['vip_buy_bili']);
                }
                $value['is_onsell'] = $cart_data['is_onsell'] = $goods_info['is_onsell'];
                // 第三步 判断是否存在规格 判断规格状态
                $spec_price_info = [];
                $spec_price_info = $specPriceModel
                ->where([['goods_id', '=', $value['goods_id']], ['sku_key', '=', $value['spec_key']], ['spec_price_id', '=', $value['spec_price_id']]])
                ->field('`selling_price`,`achievement_bili`,`bonus_price`,`next_bonus_price`,`picurl`,`stock`,`is_onsell`')
                ->find();
                // 判断完毕 涉及更改的 进行购物车数据的更新 包含产品图片等信息
                if ('' != $value['spec_key'] && !$spec_price_info) {
                    continue;
                }
                $stock = $spec_price_info ? $spec_price_info['stock'] : $goods_info['stock'];
                if ($spec_price_info) {
                    $value['goods_pic'] = $cart_data['goods_pic'] = $spec_price_info['picurl'];
                    $value['goods_price'] = $cart_data['goods_price'] = $spec_price_info['selling_price'];
                    $value['selling_price'] = $cart_data['selling_price'] = $spec_price_info['selling_price'];
                    if ($value['is_buy'] == 1) {
                        $value['goods_price'] = $cart_data['goods_price'] =
                      sprintf('%.2f', (float)$spec_price_info['selling_price']*(float)$goods_info['vip_buy_bili']);
                    }
                    $value['achievement_bili'] = $cart_data['achievement_bili'] = $spec_price_info['achievement_bili'];
                }
                $value['goods_pic'] = getShowUrl($value['goods_pic']);
                $value['goods_name'] = $value['goods_name'];
                $value['total_price'] = $value['goods_price']*$value['buy_num']; // 商品小计
                $car_res = $carModel->find($value['car_id'])->save($cart_data);
                $store_list[$store_id]['all_count'] =  isset($store_list[$store_id]['all_count']) ? $store_list[$store_id]['all_count'] : 0; // 店铺总数量
                $store_list[$store_id]['all_price'] = isset($store_list[$store_id]['all_price']) ? $store_list[$store_id]['all_price'] : 0; // 店铺总计
                $store_list[$store_id]['total_price'] = isset($store_list[$store_id]['total_price']) ? $store_list[$store_id]['total_price'] : 0; // 店铺商品小计
                $store_list[$store_id]['cost'] = isset($store_list[$store_id]['cost']) ? $store_list[$store_id]['cost'] : 0; // 店铺总运费
                $store_list[$store_id]['all_count'] += $value['buy_num'];
                $store_list[$store_id]['all_price'] += $value['total_price'];
                $store_list[$store_id]['total_price'] = round(($store_list[$store_id]['total_price']+$value['total_price']), 2);
                $store_list[$store_id]['goods_list'][] = $value;
            }

            if ($store_list) {
                foreach ($store_list as $key => $value) {
                    $cost_type = 0;
                    $cost_price = 0.00;
                    // 根据仓库 计算仓库运费
                    if ($address_info) {
                        $cost_info = $shippingServices->getCostPrice($address_info, $key, $value['all_count']);
                        $cost_type = $cost_info['cost_type'];
                        $cost_price = $cost_info['cost_price']; // 仓库总运费
                    }
                    $store_list[$key]['total_freight'] = $cost_price;
                    $store_list[$key]['all_price'] = $cost_price+$value['total_price'];
                    if ($cost_type == 1) {
                        // 按照单件计算运费 运费开始均分到每件商品
                        $all_num = array_sum(array_column($value['goods_list'], 'buy_num'));
                    } else {
                        $all_num = count($value['goods_list']);
                    }
                    $avg_cost = floor(($cost_price/$all_num)*100)/100;
                    if ($value['goods_list']) {
                        foreach ($value['goods_list'] as $k => $val) {
                            $store_list[$key]['goods_list'][$k]['cost'] = $avg_cost*$val['buy_num'];
                        }
                    }
                }
            }
            // 开始组合获取总价
            $total_price = array_sum(array_column($store_list, 'total_price'));
            $all_price = array_sum(array_column($store_list, 'all_price'));
            $cost = array_sum(array_column($store_list, 'total_freight'));
            $all_count = array_sum(array_column($store_list, 'all_count'));
            $resultData = [];
            $resultData['car_list'] = $store_list ? $store_list : [];
            $resultData['all_price'] = round($all_price, 2);
            $resultData['all_count'] = $all_count;
            $resultData['total_price'] = round($total_price, 2);
            $resultData['cost'] = round($cost, 2);
            return $resultData ? $resultData : [];
        }
    }
}
